import React from 'react';
import { nanoid } from 'nanoid';
import PropTypes from 'prop-types';
import './index.css';

export default class Header extends React.Component {
  static propTypes = {
    addTodo: PropTypes.func.isRequired
  }

  // 键盘事件  回车添加数组
  handleKeyUp = e => {
    const { keyCode, target } = e;    
    if (keyCode !== 13) return;
    if (target.value.replace(/ /g, '') === '') {
      return alert('输入不能为空!');
    }
    // 传递对象  直接进行添加就行  nanoid插件，不重复id
    const todoObj = { id: nanoid(), name: target.value, done: false };
    this.props.addTodo(todoObj);
    target.value = '';
  };

  render() {
    return (
      <div className="todo-header">
        <input type="text" placeholder="请输入你的任务名称，按回车键确认" onKeyUp={this.handleKeyUp} />
      </div>
    );
  }
}
